package sample.util;

import sample.context.ContextValues;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * @author ：five03
 * @description：TODO
 * @date ：2020/8/13 9:59 上午
 */

public class ChatSent {
    private static void send(String text,String toIP,int toPort){
        try {
            DatagramSocket socket = new DatagramSocket(ContextValues.fromPort);
            byte[] dataBytes = text.getBytes("UTF-8");
            DatagramPacket packet = new DatagramPacket(dataBytes,0,dataBytes.length,new InetSocketAddress(toIP,toPort));
            socket.send(packet);
            System.out.println("发送消息===>");
            System.out.println(text + "->" + toIP);
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void sendText(String text,String toIP,int toPort){
        String s = ContextValues.hostIp + "@" +text;
        send(s,toIP,toPort);
    }

    public static void sendStrangerText(String text,String toIP,int toPort){
        String s = ContextValues.strangerIP+ "@" +text;
        send(s,toIP,toPort);
    }

    public static void sendUserReq(String text,String toIP,int toPort){
        send(text,toIP,toPort);
    }
}
